package com.luyang.framework.protocol;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * 统一 API 响应结果封装
 *
 * @author lu_yang
 */
@Getter
@SuppressWarnings("all")
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Result<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    private int code;

    /**
     * 状态消息
     */
    private String message;

    /**
     * 状态标识
     */
    private boolean success;

    /**
     * 结果数据
     */
    private T data;

    private Result(IResultCode resultCode, String message) {
        this(resultCode, message, null);
    }

    private Result(IResultCode resultCode, String message, T data) {
        this(resultCode.getCode(), message, data);
    }

    private Result(int code, String message, T data) {
        this.code = code;
        this.data = data;
        this.message = message;
        this.success = ResultCode.SUCCESS.getCode() == code;
    }

    /**
     * 成功 无携带数据
     *
     * @return com.luyang.framework.core.protocol.Result
     * @author lu_yang
     */
    public static <T> Result<T> success() {
        return success(null);
    }

    /**
     * 成功 携带数据
     *
     * @param data 响应数据
     * @return com.luyang.framework.core.protocol.Result
     * @author lu_yang
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }

    /**
     * 失败
     *
     * @param resultCode 业务代码
     * @param message    消息
     * @return com.luyang.framework.protocol.Result
     * @author lu_yang
     */
    public static <T> Result<T> failure(ResultCode resultCode, String message) {
        return new Result<>(resultCode, message);
    }
}
